<template>
  <div class="container">
    <div class="header1" style="padding: 10px 0px">
      <div style="display: flex; justify-content: space-between">
        <div style="display: flex; justify-content: flex-start">
          <a-button class="hte-btn add-btn" type="primary" @click="handleAdd">创建</a-button>
          <a-button class="hte-btn" plain @click="handleEdit">编辑</a-button>
          <!-- <a-button class="hte-btn" plain @click="handleExport">导出</a-button> -->
          <a-button class="hte-btn" plain @click="handleDel" style="color: red">删除</a-button>
          <a-button class="hte-btn" plain @click="handleReload">刷新</a-button>
        </div>
        <div style="display: flex; justify-content: flex-start">
          <a-select v-model="keywordType" @change="changeKeywordType">
            <a-select-option value="1"> 任务名称 </a-select-option>
            <a-select-option value="2"> 类路径 </a-select-option>
          </a-select>
          <a-input-search
            v-if="keywordType == '1'"
            v-model="searchForm.taskName"
            @search="handleToSearch"
            placeholder="请按照关键字进行搜索"
          />
          <a-input-search
            v-if="keywordType == '2'"
            v-model="searchForm.classPath"
            @search="handleToSearch"
            placeholder="请按照关键字进行搜索"
          />
          <a-button class="hte-btn del-btn" @click="showSearchForm = true">高级搜索</a-button>
        </div>
      </div>
      <a-modal
        :visible="showSearchForm"
        width="70vw"
        :bodyStyle="{ padding: '10px' }"
        title="高级查询"
        @ok="handleToSearch"
        @cancel="showSearchForm = false"
      >
        <a-form-model
          ref="ruleForm"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          @keyup.enter.native="handleToSearch"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item label="任务状态">
                <a-select v-model="searchForm.status" style="width: 100%" allowClear>
                  <a-select-option value=""> 全部 </a-select-option>
                  <a-select-option v-for="(code, index) in codes.InfrastructureStatus" :key="index" :value="code.code">
                    {{ code.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="任务名称">
                <a-input allow-clear v-model="searchForm.taskName" />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="类路径">
                <a-input allow-clear v-model="searchForm.name" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-modal>
    </div>
    <div class="content-list">
      <a-table
        :scroll="{ x: 1800 }"
        :columns="columns"
        :data-source="records"
        rowKey="id"
        bordered
        :pagination="false"
        :customRow="customRow"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <template slot="statusRender" slot-scope="text, record">
          <template v-for="item in taskStatusOpt">
            <template v-if="item.code == record.status">
              {{ item.name }}
            </template>
          </template>
        </template>

        <template slot="taskTypeRender" slot-scope="text, record">
          <template v-for="item in taskTypeOpt">
            <template v-if="item.code == record.taskType">
              {{ item.name }}
            </template>
          </template>
        </template>

        <template slot="executePeroidRender" slot-scope="text, record">
          <span v-if="record.taskType == '1'"
            >每
            {{ record.executePeroid }}
            <template v-for="item in executeUnitOpt">
              <template v-if="item.code == record.executeUnit">
                {{ item.name }}
              </template>
            </template>
            执行一次</span
          >
          <span v-else> {{ record.cornExpress }}</span>
        </template>
        <template slot="triggerRender" slot-scope="text, record">
          <a-button @click="triggerJob(record)">执行</a-button>
        </template>
      </a-table>
      <a-pagination
        show-size-changer
        :default-current="1"
        :total="searchForm.total"
        @change="pageChange"
        @showSizeChange="onShowSizeChange"
        :show-total="(total) => `共 ${total} 条记录`"
      />
    </div>
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { formatDate, parseTime } from '@/utils/util'
import { UtilsMixin } from '@/mixins/UtilsMixin'
export default {
  mixins: [UtilsMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
  },
  data() {
    return {
      currUserId: this.$store.getters.userInfo.username,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      urls: {
        list: '/hteQuartz/page',
        codes: '/manage/codeInfo/queryByTypes',
        delete: '/hteQuartz/delete',
        triggerJob: '/hteQuartz/trigger',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      keywordType: '1',
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      taskTypeOpt: [
        { code: '1', name: '循环任务' },
        { code: '2', name: '定时任务' },
      ],
      taskEnvOpt: [
        { code: '全部', name: '全部环境' },
        { code: 'dev', name: '开发环境' },
        { code: 'test', name: '测试环境' },
        { code: 'prod', name: '正式环境' },
      ],
      executeUnitOpt: [
        { code: '1', name: '秒' },
        { code: '2', name: '分' },
        { code: '3', name: '时' },
      ],
      taskStatusOpt: [
        { code: '1', name: '开启' },
        { code: '2', name: '关闭' },
      ],
      searchForm: {
        pageNo: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
        isCancel: 0,
      },
      codes: {},
      records: [],
      columns: [
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusRender' },
          width: '80px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '任务名称',
          dataIndex: 'taskName',
          width: '200px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '类路径',
          dataIndex: 'classPath',
          width: '280px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '任务类型',
          dataIndex: 'taskType',
          align: 'center',
          width: '120px',
          ellipsis: true,
          scopedSlots: { customRender: 'taskTypeRender' },
        },
        {
          title: '任务周期',
          dataIndex: 'executePeroid',
          align: 'center',
          width: '160px',
          ellipsis: true,
          scopedSlots: { customRender: 'executePeroidRender' },
        },
        {
          title: '上次执行时间',
          dataIndex: 'lastExecuteTime',
          align: 'center',
          width: '160px',
          ellipsis: true,
        },
        {
          title: '上次执行状态',
          dataIndex: 'lastExecuteResult',
          align: 'center',
          width: '160px',
          ellipsis: true,
        },
        {
          title: '下次执行时间',
          dataIndex: 'nextExecuteTime',
          align: 'center',
          width: '160px',
          ellipsis: true,
        },
        {
          title: '立即执行',
          align: 'center',
          width: '120px',
          ellipsis: true,
          scopedSlots: { customRender: 'triggerRender' },
        },
      ],
      showSearchForm: false,
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  async mounted() {
    this.fetchList()
    await this.fetchCodes()
  },
  methods: {
    formatDate,
    changeKeywordType() {
      if (this.keywordType == '1') {
        this.$set(this.searchForm, 'name', '')
      } else {
        this.$set(this.searchForm, 'applyNo', '')
      }
    },
    fetchCodes() {
      let types = []
      types.push('定时任务状态')
      types.push('定时任务类型')
      getAction(this.urls.codes, { types: types.join(',') }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    fetchList() {
      postAction(this.urls.list, this.searchForm).then((res) => {
        if (res.success) {
          this.records = res.result.records
          this.$set(this.searchForm, 'total', res.result.total)
        } else {
          this.$message.error('查询数据错误:' + res.message)
        }
      })
    },
    handleAdd() {
       this.$router.push('/quartz/add' )
    },
    handleEdit() {
      if (!this.selectedRows || this.selectedRows.length <= 0) {
        return this.$message.warning('请选择一条记录操作')
      }
      this.$router.push('/quartz/edit?id=' + this.selectedRows[0].id)
    },
    handleDel() {
      if (!this.selectedRows || this.selectedRows.length != 1) {
        return this.$message.warning('请选择一条记录操作')
      }
      // let applyNos = []
      // for (let r of this.selectedRows) {
      //   applyNos.push(r.applyNo)
      //   if (r.status == '2') {
      //     return this.$message.warning('请勿删除审批通过的基建现场管理单')
      //   }
      //   if ([1, 3].indexOf(r.status) >= 0 && r.applyUserId == this.currUserId) {
      //     return this.$message.warning('审批中或审批不通过只能由流程发起人执行删除')
      //   }
      // }
      let that = this
      this.$confirm({
        content: `是否确定删除定时任务？`,
        onOk: () => {
          getAction(that.urls.delete + '/' + that.selectedRowKeys.join(',')).then((res) => {
            if (res.success) {
              that.selectedRows = []
              that.selectedRowKeys = []
              that.$message.success('删除成功')
              that.fetchList()
            } else {
              that.$message.error('删除失败:' + res.message)
            }
          })
        },
      })
    },
    handleReload() {
      this.fetchList()
    },
    handleToSearch() {
      this.searchForm.pageNo = 1
      this.showSearchForm = false
      this.fetchList()
    },
    handleExport() {
      this.searchForm.selectedIds = this.selectedRowKeys.join(',')
      let url = process.env.VUE_APP_API_BASE_URL + '/infrastructure/export?1=1'
      this.handleExportXls(parseTime(new Date(), '{y}{m}{d}') + '《定时任务列表》', url, this.searchForm)
    },
    pageChange(pageNo, pageSize) {
      this.$set(this.searchForm, 'pageSize', pageSize)
      this.$set(this.searchForm, 'pageNo', pageNo)
      this.fetchList()
    },
    onShowSizeChange(pageNo, pageSize) {
      this.searchForm.pageNo = 1
      this.searchForm.pageSize = pageSize
      this.fetchList()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    customRow(record) {
      return {
        on: {
          dblclick: (event) => {
            if (!this.selectedRowKeys) {
              this.selectedRowKeys = []
              this.selectedRows = []
            }
            if (this.selectedRowKeys.indexOf(record.id) <= -1) {
              this.selectedRows.push(record)
              this.selectedRowKeys.push(record.id)
            } else {
              let index = this.selectedRowKeys.indexOf(record.id)
              this.selectedRowKeys.splice(index, 1)
              this.selectedRows.splice(index, 1)
            }
          },
        },
      }
    },
    triggerJob(record) {
      let that = this
      this.$confirm({
        content: '是否立即执行[' + record.taskName + ']一次？',
        onOk: () => {
          getAction(this.urls.triggerJob + '?id=' + record.id).then((res) => {
            if (res.success) {
              that.$message.success('执行成功')
              that.fetchList()
            } else {
              that.$message.success('执行失败:' + res.message)
            }
          })
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.container {
  .content {
    margin-top: 20px;

    section {
      margin-bottom: 18px;

      .section-table {
        .add-btn {
          margin-left: 0;
          margin-bottom: 10px;
        }

        /deep/ .a-upload__input {
          display: none !important;
        }
      }
    }
  }
}

.tips-box {
  margin-top: 32px;

  .add-btn {
    width: 180px;
    height: 40px;
    line-height: 40px;
    background-color: #4095e4;
    border-radius: 2px;
  }
}

/deep/ .el-upload__input {
  display: none !important;
}
</style>
